<template>
  <!-- 相册内容 -->
  <div>
    <!-- 相册头部 -->
    <div class="gallery-header">
      <!-- 返回功能 -->
      <div>
        <slot name="back"></slot>
      </div>
      <!-- 删除图库 -->
      <div class="ganllery-delete">
        <button
          @click="mask = true"
          style="font-size: 16px; background: #fff; border: 0"
        >
          删除图库
        </button>
      </div>
    </div>

    <!-- 相册内容 -->
    <el-main class="gallery-main">
      <!-- 相册信息 -->
      <span style="font-size: 20px">{{ val.galleryName }}</span>

      <!-- 相册容器 -->
      <div class="photo-container">

        <!-- img回显，绑定click事件单机删除-->
        <div
          :key="index"
          v-for="(item, index) in galleryList"
          class="Countainerimg"
        >
          <img :src="item" class="img-name" />
          <i class="el-icon-close" @click="deleteImg(index, item)"></i>
        </div>

        <el-upload
          :action="uploadImgUrl"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :before-upload="beforeAvatarUpload"
          :auto-upload="true"
          :limit="limit"
          multiple
          :on-error="handleUploadError"
          ref="imageUpload"
          :on-remove="handleDelete"
          :show-file-list="true"
          :headers="headers"
          :file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :class="{ hide: this.fileList.length >= this.limit }"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" alt="" />
        </el-dialog>
      </div>
    </el-main>

    <el-main class="mask" v-if="mask">
      <div class="mask-background">
        <div class="mask-top">主题名称</div>

        <div class="mask-middle">
          <span>你确定删除此图库吗？</span>
        </div>

        <div class="mask-bottom">
          <button class="bottom-left" @click="submit()">确定</button>
          <button class="bottom-right" @click="mask = false">取消</button>
        </div>
      </div>
    </el-main>
  </div>
</template>

<script>
import popupWindow from "../../components/popupWindow/window";
import { deleteGallery } from "@/api/myInfoTeacher/gradegallery";
import { deleteImage, photoimageAPI } from "@/api/make/make";
import { getToken } from "@/utils/auth";
import module from "@/allurlimg/img";
import * as imageConversion from 'image-conversion'

export default {
  components: {
    popupWindow,
  },
  props: {
    val: {
      type: "",
      default: "",
    },
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },

  data() {
    return {
      newVal: this.val,
      mask: false,

      galleryList: [],
      curIndex: 0,
      fileList: [],
      uploadList: [],
      photoList: [{ url: "" }],
      dialogImageUrl: "",
      studentId: "",
      galleryId: this.val.galleryId,
      dialogVisible: false,
      hideUpload: false,
      uploadImgUrl:
        "process.env.VUE_APP_BASE_API + `/business/gallery/upload/`+this.remark",
      headers: {
        Authorization: "Bearer " + getToken(),
      },

      deleteIndex: "",
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              if (item.indexOf(this.baseUrl) === -1) {
                item = { name: this.baseUrl + item, url: this.baseUrl + item };
              } else {
                item = { name: item, url: item };
              }
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  //开启挂载
  async created() {
    this.func1();
    this.getAllGallery();
  },

  methods: {
    setIndex(index) {
      this.curIndex = index;
    },

    //数组对比，单击删除事件
    deleteImg(index, item) {
      this.deleteIndex = index;
      if (this.deleteIndex == index) {
        console.log(item);
        const a = item[0].split("dev-api")[1];
        this.deImage(a);
      }
    },

    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log("9999", res);
      console.log("3333", file);
      if (res.code === 200) {
        this.uploadList.push({ name: file.name, url: file.url });
        console.log("2222", this.uploadList, file.url);
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    
      //图片上传前，进行图片校验
      beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg/png";
      const isLt1M = (file.size / 1024 / 1024) * 10 < 6;
      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 和 PNG 格式!");
      // }
      if (!isLt1M) {
        this.$message.warning("上传头像图片大小不能超过 600kb! 将进行压缩");
        let myImg = new Promise((resolve) => {
          // 压缩到500KB,这里的500就是要压缩的大小,可自定义
          imageConversion.compressAccurately(file, 500).then((res) => {
            resolve(res);
          });
        });
        console.log(myImg);
        return myImg;
      }
      return isLt1M;
    },

    //删除
    handleDelete() {

    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      // if (this.number > 0 && this.uploadList.length === this.number) {
      this.fileList = this.fileList.concat(this.uploadList);
      console.log(this.fileList, "fileList");
      console.log("6666", this.fileList[1]);
      this.uploadList = [];
      this.$emit("input", this.listToString(this.fileList));
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },

    // 回显图片
    async getAllGallery() {
      this.galleryList = [];

      const res = await photoimageAPI({ galleryId: this.galleryId });
      console.log("11", res);
      for (const index in res["data"]) {
        this.galleryList.push([
          module.host + res["data"][index],
        ]);
      }
      console.log(this.galleryList);
    },
    //element-ui要改的post请求
    async func1() {
      this.uploadImgUrl =
        process.env.VUE_APP_BASE_API +
        `/business/gallery/upload/` +
        this.galleryId;
      // const res=await photoimageAPI({galleryId:this.galleryId})
      // let urls='http://localhost/dev-api'+res.data
      // console.log(urls)
    },
    //delete接口调用，并回显img
    async deImage(data) {
      const res = await deleteImage(data);
      this.getAllGallery();
    },

    // 提交
    submit() {
      Promise.all([
        this.mask = !this.mask,
        this.deleteClassGallery(this.val.galleryId),
        this.$parent.$parent.getClassGallery()
      ]).then(res => {
        // 提交后返回图库
        this.$parent.$parent.switchDisplay(0)

      })
    },

    // 删除图库并清空图库图片
    async deleteClassGallery(galleryId) {
      const res = await deleteGallery(galleryId);
      console.log(res, "clear");
    },
  },
};
</script>

<style>
/* 相册头部 */
.gallery-header {
  margin: 1.25rem;
  display: flex;
  flex-direction: row;
  position: relative;
}

/* 删除相册 */
.ganllery-delete {
  position: absolute;
  right: 0;
}

/* 相册内容 */
.gallery-main {
  margin: 0 1.25rem;
  display: flex;
  flex-direction: column;
  height: 40rem;
  overflow: hidden;
  overflow-y: scroll;
}

/* 相册容器 */
.photo-container {
  margin: .625rem 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  color: rgb(red, green, blue);
}

/* 添加照片 */
.photo-add {
  display: flex;
  margin: .625rem;
  border-radius: 5px;
  justify-content: center;
  align-items: center;
}
.images {
  width: 9.25rem;
  height: 9.25rem;
}

.mask {
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  display: flex;
  position: absolute;
  align-items: center;
  justify-content: center;
  background: rgba(56, 55, 55, 0.651);
  z-index: 9;
}

.mask-background {
  width: 25rem;
  height: 12.5rem;
  display: flex;
  border-radius: 10px;
  background: #fff;
  flex-direction: column;
  border: 2px solid rgba(56, 55, 55, 0.3);
}

.mask-top {
  top: 0px;
  width: 100%;
  padding: .3125rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgba(56, 55, 55, 0.1);
}

.mask-middle {
  display: flex;
  width: 100%;
  height: 5rem;
  align-items: center;
  justify-content: center;
  margin: .375rem 0px .625rem 0px;
}

.middle-input {
  width: 21.25rem;
  height: 3.125rem;
  border-radius: 5px;
  border: 1px solid rgba(56, 55, 55, 0.5);
}

.mask-bottom {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.bottom-left {
  width: 7.5rem;
  height: 3rem;
  display: flex;
  border-radius: 5px;
  align-items: center;
  justify-content: center;

  border: 0px;
  color: #ffffff;
  background: #7c0000;
}

.bottom-right {
  width: 7.5rem;
  height: 3.125rem;
  display: flex;
  border-radius: 5px;
  align-items: center;
  justify-content: center;

  color: #000000;
  margin-left: 3.75rem;
  background: #ffffff;
  border: 1px solid rgba(56, 55, 55, 0.3);
}
.Countainerimg {
  position: relative;
  width: 9.25rem;
  height: 9.25rem;
  margin: .625rem;
}
.el-icon-close {
  top: 0;
  right: 0;
  position: absolute;
  z-index: 2;
  color: rgba(1, 1, 1, 0.6);
  font-size: 1.625rem;
}
.img-name {
  position: relative;
  display: flex;
  width: 9.25rem;
  height: 9.25rem;
  z-index: 1;
}
</style>